package com.xinqi.common.mybatis.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.xinqi.common.base.constants.C;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.ObjectProvider;

import java.time.LocalDateTime;
import java.util.Objects;
import java.util.Optional;

/**
 * 注入公共字段自动填充,任选注入方式即可
 *
 * @author linkai
 */
@Slf4j
public class BaseMetaObjectHandler implements MetaObjectHandler {

    private final Long defaultUser = C.DEFAULT_USER_ID;

    private final CurrentUser currentUser;

    public BaseMetaObjectHandler(ObjectProvider<CurrentUser> currentUser) {
        this.currentUser = currentUser.getIfAvailable();
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        LocalDateTime dateTime = LocalDateTime.now();
        // 添加创建时间、修改时间
        setFieldValByName("createTime", dateTime, metaObject);
        setFieldValByName("updateTime", dateTime, metaObject);

        // 添加创建人、修改人
        Object createBy = getFieldValByName("createBy", metaObject);
        Object userId = Objects.isNull(createBy) ? defaultUser : createBy;
        Object id = Optional.ofNullable(currentUser).map(v -> v.getCurrentUserId().orElse(userId))
            .orElse(userId);
        setFieldValByName("createBy", id, metaObject);
        setFieldValByName("updateBy", id, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        LocalDateTime dateTime = LocalDateTime.now();
        // 更新修改时间
        setFieldValByName("updateTime", dateTime, metaObject);
        // 更新修改人
        Object updateBy = getFieldValByName("updateBy", metaObject);
        Object userId = Objects.isNull(updateBy) ? defaultUser : updateBy;
        Object id = Optional.ofNullable(currentUser).map(v -> v.getCurrentUserId().orElse(userId))
            .orElse(userId);
        setFieldValByName("updateBy", id, metaObject);
    }

}
